#include "../lib/listner.hpp"
#include <sys/poll.h>
#include <sys/time.h>
#include <unistd.h>

using namespace kport;
using pland::utill_log;
using pland::utill_to_string;
using pland::Exeption;

Listner::Listner(int sock, pland::SharedDQueue qout)
{
	sock_ = sock;
	qout_ = qout;
}

Listner::~Listner()
{
	::close(sock_);
}

bool Listner::ready() throw(Exeption)
{
	struct pollfd fds;
	int status;
	fds.fd = sock_;
	fds.events = POLLIN | POLLPRI;
	status = ::poll(&fds, 1, 0);
	if(status == -1)
	{
		utill_log(std::string(__FILE__) + " KPort Listener data recieve failed. Errno " + utill_to_string(errno));
		throw Exeption("Poll system call failed", PEXP_FATAL);
	}
	if(status == 0)
		return false;
	return true;
}

WorkItemStat Listner::work()  throw(Exeption)
{
	int status;
	pland::Data_Header* header = new pland::Data_Header;
	status = pland::utill_io_read(sock_,(char*)header, sizeof(pland::Data_Header));
	if(status != sizeof(pland::Data_Header))
	{
		utill_log(std::string(__FILE__) + " KPort Listener data recieve failed. Errno " + utill_to_string(errno));
		throw Exeption("Could not read from socket", PEXP_FATAL);
	}
	char* buff = new char[header->size];
	status = pland::utill_io_read(sock_,(char*)buff, header->size);
	if(status != header->size)
	{
		utill_log(std::string(__FILE__) + " KPort Listener data recieve failed. Errno " + utill_to_string(errno));
		throw Exeption("Could not read from socket", PEXP_FATAL);
	}
    struct timeval now;
    gettimeofday(&now, NULL);
    header->secLocal = now.tv_sec;
    header->usecLocal = now.tv_usec;

	pland::SharedData d(new pland::Data(buff, header));
	struct WorkItemStat ret;

    ret.secTime = now.tv_sec;
    ret.usecTime = now.tv_usec;
    ret.secLatency = 0;
    ret.usecLatency = 0;
	ret.bytes = sizeof(pland::Data_Header) + header->size;
	ret.items = 1;
	qout_->push(d);
	return ret;
}
